package hhm.framessm.authority.interceptor;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import hhm.framessm.authority.service.PermissionService;
import hhm.framessm.authority.service.RoleService;
import hhm.framessm.pojo.TbPermission;
import hhm.framessm.pojo.TbResource;
import hhm.framessm.pojo.TbRole;
import hhm.framessm.pojo.TbUser;

public class BaseInterceptor implements HandlerInterceptor {

	@Autowired
	private PermissionService permissionService;
	@Autowired
	private RoleService roleService;

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// 判断要访问的资源是否需要权限
		String requestURI = request.getRequestURI();
		TbResource resource = permissionService.findResourceByURI(requestURI);

		// 如果不需要权限放行
		if (resource == null) {
			return true;

		}

		TbPermission permission = resource.getTbPermission();

		// 这里获取user，不写了
		TbUser user = new TbUser();
		user.setUserId(1);
		Set<TbRole> set = new HashSet<TbRole>();
		TbRole role = new TbRole();
		role.setRoleId(1);

		set.add(role);
		user.setRoles(set);

		List<TbPermission> userPermission = getUserPermission(user);

		// 如果有权访问则放行
		if (userPermission.contains(permission)) {

			return true;
		} else {
			return false;
		}

	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
			ModelAndView modelAndView) throws Exception {
		// handler执行之后，返回ModelAndView之前

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
			throws Exception {
		// 返回ModelAndView之后。
		// 响应用户之后。

	}

	private List<TbPermission> getUserPermission(TbUser user) {
		List<TbPermission> list = new ArrayList<TbPermission>();
		Set<TbRole> roles = user.getRoles();
		for (TbRole role : roles) {

			list.addAll(roleService.findRoleById(role.getRoleId()).getTbPermissions());
		}
		return list;
	}

}
